package com.ebc.eservice.service.cardStat;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ebc.eservice.mapper.CompanySectorMapper;
import com.ebc.eservice.mapper.EbcCardStatMapper;
import com.ebc.eservice.mapper.InteractClientMapper;
import com.ebc.eservice.mapper.RoleMapper;
import com.ebc.eservice.pojo.EbcCardStat;
import com.ebc.eservice.pojo.EbcCompanySector;
import com.ebc.eservice.pojo.EbcInteractClient;
import com.ebc.eservice.pojo.EbcRole;
import com.ebc.eservice.util.DemicalUtil;
import com.ebc.eservice.util.JsonResult;
import com.ebc.eservice.util.JwtUtil;
import com.ebc.eservice.util.MyTimeUtil;
import com.ebc.eservice.vo.card.CardInfoVo;
import com.ebc.eservice.vo.card.CardStatReqVo;
import com.ebc.eservice.vo.card.history.CardHistoryReqVo;
import com.ebc.eservice.vo.card.history.AverageCardStat;
import com.ebc.eservice.vo.card.history.PerCardStat;
import com.ebc.eservice.vo.card.history.TotalCardStat;
import com.ebc.eservice.vo.card.totalStat.SectorStatDto;
import com.ebc.eservice.vo.card.totalStat.SectorStatRespVo;
import com.ebc.eservice.vo.card.totalStat.TotalRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HyperLogLogOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author: Joey
 * @Description: 名片数据统计业务
 * @date:2022/9/27 15:58
 */
@Service
public class CardStatImp implements CardStatService{

    @Autowired
    private EbcCardStatMapper ebcCardStatMapper;
    @Autowired
    private CompanySectorMapper companySectorMapper;
    @Autowired
    private InteractClientMapper clientMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RoleMapper roleMapper;

    //获取近7天访客趋势+访客概况（访客总量、近7日访客、今日访客）
    @Override
    public JsonResult getVisitStat(Integer cardId) {
        MyTimeUtil timeUtil = new MyTimeUtil();
        List<String> sevenDayEx = timeUtil.getSevenDayExYear();//09-12
        List<String> sevenDay = timeUtil.getSevenDay();
        String today = timeUtil.getToDay();
        List<Integer> visitList = new ArrayList<Integer>();
        HashMap<String, Object> mapVo = new HashMap<>();
        //今日
        Map<String,Object> mapToday = redisTemplate.opsForHash()
                .entries("card:"+cardId+":date:"+today);
        int cardTodays=0;
        if(mapToday.size()==0){
//            mapVo.put("null","暂时无数据");
//            return JsonResult.error("无数据",mapVo);
            cardTodays=0;
        }else{
            cardTodays = (int) mapToday.get("visit");
        }

        //7日
        for (int i = 0; i <  sevenDay.size() ; i++) {
            Map<String,Object> map = redisTemplate.opsForHash()
                    .entries("card:"+cardId+":date:"+sevenDay.get(i));
            if(map.size()==0){
                visitList.add(0);
                continue;
            }
            int card = (int) map.get("visit");
            visitList.add(card);
        }
        int num = 0;
        List<Integer> perDayData = new ArrayList<Integer>();
        for (Integer integer : visitList) {
            num = num + integer;
            perDayData.add(integer);
        }

        //总访客数
        TotalCardStat totalStat = ebcCardStatMapper.getCardTotalStat(cardId);
        int TotalVisitNum = 0;
        if(totalStat==null){
            TotalVisitNum = 0;
        }else{
            TotalVisitNum = totalStat.getVisitNum();
        }

        mapVo.put("VisitTotalNum",TotalVisitNum);//访客总量
        mapVo.put("TodayVisit",cardTodays);//今日访客
        mapVo.put("TimeList",sevenDayEx); //近7天时间列表
        mapVo.put("VisitNumSevenDay",num);//近7天访客总数
        mapVo.put("PerDayData",perDayData);//近7天每日数据
        return JsonResult.success(mapVo);
    }

    //保存名片
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveCard(CardStatReqVo cardStatVo) {//downLoadNum
        MyTimeUtil timeUtil = new MyTimeUtil();
        String today = timeUtil.getToDay();
        //redis 名片访客 +1                      格式： card:1:date:09-20,< visit ,1 >
        redisTemplate.opsForHash().increment("card:"+cardStatVo.getCardId()+":date:"+today,
                "downLoadNum", 1);
        //redis  客户数量记录+1 自动去重
        HyperLogLogOperations<String, String> clientVo = redisTemplate.opsForHyperLogLog();
        clientVo.add("cardclient:"+cardStatVo.getCardId()+":date:"+today,"user:"+cardStatVo.getUserId());

        //名片
        QueryWrapper<EbcCardStat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_flag",today);
        queryWrapper.eq("card_id",cardStatVo.getCardId());
        EbcCardStat cardStat = ebcCardStatMapper.selectOne(queryWrapper);
        if(cardStat != null){
            ebcCardStatMapper.addDownload(today);
        }else{  //不为空则更新+1
            return JsonResult.fail("当日未登录,addDownload-生成记录无效");
        }
        //客户
        QueryWrapper<EbcInteractClient> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("create_inter_time",today);
        queryWrapper2.eq("user_id",cardStatVo.getUserId());
        queryWrapper2.eq("card_id",cardStatVo.getCardId());
        EbcInteractClient selectClient = clientMapper.selectOne(queryWrapper2);
        if(selectClient != null){//客户第一次访问
            clientMapper.updateInteractNum(today,cardStatVo.getUserId());
//            EbcInteractClient client = new EbcInteractClient();
//            client.setCardId(cardStatVo.getCardId()).setUserId(cardStatVo.getUserId())
//                    .setCreateInterTime(today).setInteractNum(1);
//            clientMapper.insert(client);
        }
        return JsonResult.success("后台记录成功,CARD-addDownload");
    }

    //添加通讯录
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addContacts(CardStatReqVo cardStatVo) {//addContactNum
        MyTimeUtil timeUtil = new MyTimeUtil();
        String today = timeUtil.getToDay();
        //redis 名片访客 +1                      格式： card:1:date:09-20,< visit ,1 >
        redisTemplate.opsForHash().increment("card:"+cardStatVo.getCardId()+":date:"+today,
                "addContactNum", 1);
        //redis  客户数量记录+1 自动去重
        HyperLogLogOperations<String, String> clientVo = redisTemplate.opsForHyperLogLog();
        clientVo.add("cardclient:"+cardStatVo.getCardId()+":date:"+today,"user:"+cardStatVo.getUserId());

        //名片
        QueryWrapper<EbcCardStat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_flag",today);
        queryWrapper.eq("card_id",cardStatVo.getCardId());
        EbcCardStat cardStat = ebcCardStatMapper.selectOne(queryWrapper);
        if(cardStat != null){
            ebcCardStatMapper.addContact(today);
        }else{
            return JsonResult.fail("当日未登录,addContactNum-生成记录无效");
        }
        //客户
        QueryWrapper<EbcInteractClient> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("create_inter_time",today);
        queryWrapper2.eq("user_id",cardStatVo.getUserId());
        queryWrapper2.eq("card_id",cardStatVo.getCardId());
        EbcInteractClient selectClient = clientMapper.selectOne(queryWrapper2);
        if(selectClient == null){//客户第一次访问
            EbcInteractClient client = new EbcInteractClient();
            client.setCardId(cardStatVo.getCardId()).setUserId(cardStatVo.getUserId())
                    .setCreateInterTime(today).setInteractNum(1);
            clientMapper.insert(client);
        }else{ //不为空则更新+1
            clientMapper.updateInteractNum(today,cardStatVo.getUserId());
        }
        return JsonResult.success("后台记录成功,CARD-addContactNum");
    }

    //转发名片。
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult reposeCard(CardStatReqVo cardStatVo) {
        MyTimeUtil timeUtil = new MyTimeUtil();
        String today = timeUtil.getToDay();
        //redis 名片访客 +1                      格式： card:1:date:09-20,< visit ,1 >
        redisTemplate.opsForHash().increment("card:"+cardStatVo.getCardId()+":date:"+today,
                "reposeCardNum", 1);
        //redis  客户数量记录+1 自动去重
        HyperLogLogOperations<String, String> clientVo = redisTemplate.opsForHyperLogLog();
        clientVo.add("cardclient:"+cardStatVo.getCardId()+":date:"+today,"user:"+cardStatVo.getUserId());

        //名片
        QueryWrapper<EbcCardStat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_flag",today);
        queryWrapper.eq("card_id",cardStatVo.getCardId());
        EbcCardStat cardStat = ebcCardStatMapper.selectOne(queryWrapper);
        if(cardStat != null){
            ebcCardStatMapper.addForward(today);
        }else{
            return JsonResult.fail("当前未登录,addForward-生成记录无效");
        }
        //客户
        QueryWrapper<EbcInteractClient> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("create_inter_time",today);
        queryWrapper2.eq("user_id",cardStatVo.getUserId());
        queryWrapper2.eq("card_id",cardStatVo.getCardId());
        EbcInteractClient selectClient = clientMapper.selectOne(queryWrapper2);
        if(selectClient == null){//客户第一次访问
            EbcInteractClient client = new EbcInteractClient();
            client.setCardId(cardStatVo.getCardId()).setUserId(cardStatVo.getUserId())
                    .setCreateInterTime(today).setInteractNum(1);
            clientMapper.insert(client);
        }else{ //不为空则更新+1
            clientMapper.updateInteractNum(today,cardStatVo.getUserId());
        }
        return JsonResult.success("后台记录成功,CARD-addForward");
    }

    //复制微信号
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult copyWeChat(CardStatReqVo cardStatVo) {
        MyTimeUtil timeUtil = new MyTimeUtil();
        String today = timeUtil.getToDay();
        //redis 名片访客 +1                      格式： card:1:date:09-20,< visit ,1 >
        redisTemplate.opsForHash().increment("card:"+cardStatVo.getCardId()+":date:"+today,
                "copyWxAccount", 1);
        //redis  客户数量记录+1 自动去重
        HyperLogLogOperations<String, String> clientVo = redisTemplate.opsForHyperLogLog();
        clientVo.add("cardclient:"+cardStatVo.getCardId()+":date:"+today,"user:"+cardStatVo.getUserId());

        //名片
        QueryWrapper<EbcCardStat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date_flag",today);
        queryWrapper.eq("card_id",cardStatVo.getCardId());
        EbcCardStat cardStat = ebcCardStatMapper.selectOne(queryWrapper);
        if(cardStat != null){
            ebcCardStatMapper.addCopyWx(today);
        }else{
            return JsonResult.fail("当前未登录,copyWxAccount-生成记录无效");
        }
        //客户
        QueryWrapper<EbcInteractClient> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("create_inter_time",today);
        queryWrapper2.eq("user_id",cardStatVo.getUserId());
        queryWrapper2.eq("card_id",cardStatVo.getCardId());
        EbcInteractClient selectClient = clientMapper.selectOne(queryWrapper2);
        if(selectClient == null){//客户第一次访问
            EbcInteractClient client = new EbcInteractClient();
            client.setCardId(cardStatVo.getCardId()).setUserId(cardStatVo.getUserId())
                    .setCreateInterTime(today).setInteractNum(1);
            clientMapper.insert(client);
        }else{ //不为空则更新+1
            clientMapper.updateInteractNum(today,cardStatVo.getUserId());
        }
        return JsonResult.success("后台记录成功,CARD-copyWxAccount");
    }

    /************************************
     *          历史数据统计
     * *********************************/

    @Override
    public JsonResult getCardHistoryStat(CardHistoryReqVo ReqVo) {

        List<PerCardStat> PerCardStats = new ArrayList<>();//某天数据 列表
        List<TotalCardStat> TotalCardStats = new ArrayList<>();//总数
        List<AverageCardStat> averageCardStatList = new ArrayList<>();//日均
        MyTimeUtil timeUtil = new MyTimeUtil();

        String beginDate = timeUtil.toDateString(ReqVo.getBeginDate());
        String endDate = timeUtil.toDateString(ReqVo.getEndDate());
        JsonResult result=null;
        if(ReqVo.getFlag()==0){//查询日期
            System.out.println("=================查询日期========================="+beginDate+","+endDate);
            // 1、总数  mysql获取  日期计算
            TotalCardStat historyTotoalByDate = ebcCardStatMapper
                    .getCardHistoryByDate(ReqVo.getCardId(),
                            beginDate, endDate);

            if(historyTotoalByDate==null){
                System.out.println("日期为空！！！！！！！！！！！！！");
                HashMap<Object, Object> statMap = new HashMap<>();
                statMap.put("TotalCardStats",Collections.emptyList());
                statMap.put("averageCardStatList",Collections.emptyList());
                statMap.put("visitList",Collections.emptyList());
                return JsonResult.success(statMap);
            }
            TotalCardStats.add(historyTotoalByDate);
            // 2、时间段

            //天数
            int dateDist = timeUtil.getDateDist(ReqVo.getBeginDate(), ReqVo.getEndDate());
            //日期列表
            List<String> dateList = timeUtil.getAppointDateList(ReqVo.getEndDate(), dateDist);// 结束日期-天数

//        System.out.println(dateList);
            //存放某天数据对象
            List<PerCardStat> visitList = new ArrayList<PerCardStat>();
            PerCardStat perCardStat = null;
            for (int i = 0; i <  dateList.size() ; i++) {
                // k1
                Map<String,Object> map = redisTemplate.opsForHash()
                        .entries("card:"+ReqVo.getCardId()+":date:"+dateList.get(i));
                perCardStat = new PerCardStat();

                if(map.size()==0){//没找到为空
//                visitList.add(perCardStat);
                    continue;
                }else{
                    if(map.get("visit")!=null){
                        int visitNum = (int) map.get("visit");
                        perCardStat.setVisitNum(visitNum);
                    }
                    if(map.get("stayNum")!=null){
                        int stayNum = (int) map.get("stayNum");
                        perCardStat.setStayNum(stayNum);
                    }
                    if(map.get("downLoadNum")!=null){
                        int downLoadNum = (int) map.get("downLoadNum");
                        perCardStat.setDownLoadNum(downLoadNum);
                    }
                    if(map.get("addContactNum")!=null){
                        int addContactNum = (int) map.get("addContactNum");
                        perCardStat.setAddContactNum(addContactNum);
                    }
                    if(map.get("reposeCardNum")!=null){
                        int reposeCardNum = (int) map.get("reposeCardNum");
                        perCardStat.setReposeCardNum(reposeCardNum);
                    }
                    if(map.get("copyWxAccount")!=null){
                        int copyWxAccountNum = (int) map.get("copyWxAccount");
                        perCardStat.setCopyWxAccount(copyWxAccountNum);
                    }
                    if(map.get("messageNum")!=null){
                        int messageNum = (int) map.get("messageNum");
                        perCardStat.setMessageNum(messageNum);
                    }
                    perCardStat.setPerDate(dateList.get(i));
                }
                // k2
                //加进列表对象
                visitList.add(perCardStat);
            }
            // 3、日均  总天数/各项数据总数
            double totaldays = dateList.size();
            double AvgVisitNum = (historyTotoalByDate.getVisitNum()) / totaldays ;
            double AvgStayNum = (historyTotoalByDate.getStayNum()) / totaldays;
            double AvgDownloadNum = (historyTotoalByDate.getDownLoadNum()) / totaldays;
            double AvgAddContactNum =(historyTotoalByDate.getAddContactNum()) / totaldays;
            double AvgReposeCardNum =  (historyTotoalByDate.getReposeCardNum()) / totaldays;
            double AvgMessageNum = (historyTotoalByDate.getMessageNum()) / totaldays;

            //转换小数点
            DemicalUtil demicalUtil = new DemicalUtil();

            AverageCardStat averageCardStat = new AverageCardStat();
            averageCardStat.setVisitNum(demicalUtil.DoubleFormat(AvgVisitNum))
                    .setStayNum(demicalUtil.DoubleFormat(AvgStayNum))
                    .setAddContactNum(demicalUtil.DoubleFormat(AvgAddContactNum))
                    .setDownLoadNum(demicalUtil.DoubleFormat(AvgDownloadNum))
                    .setReposeCardNum(demicalUtil.DoubleFormat(AvgReposeCardNum))
                    .setMessageNum(demicalUtil.DoubleFormat(AvgMessageNum));

            //日均列表 1个
            averageCardStatList.add(averageCardStat);
            HashMap<Object, Object> statMap = new HashMap<>();
            statMap.put("TotalCardStats",TotalCardStats);//累计
            statMap.put("averageCardStatList",averageCardStatList);//日均
            statMap.put("visitList",visitList);//日期列表数据
            result = JsonResult.success(statMap);
        }
        if(ReqVo.getFlag()==1){//全部日期
            System.out.println("=================全部日期========================="+beginDate+","+endDate);
            // 1、总数  mysql获取  日期计算
            TotalCardStat historyTotoalByDate = ebcCardStatMapper
                    .getCardHistoryByDate(ReqVo.getCardId(),
                            beginDate, endDate);

            if(historyTotoalByDate==null){
                System.out.println("日期为空！！！！！！！！！！！！！");
                HashMap<Object, Object> statMap = new HashMap<>();
                statMap.put("TotalCardStats",Collections.emptyList());
                statMap.put("averageCardStatList",Collections.emptyList());
                statMap.put("visitList",Collections.emptyList());
                return JsonResult.success(statMap);
            }
            TotalCardStats.add(historyTotoalByDate);

            // 2、时间段
            //天数
            int dateDist = timeUtil.getDateDist(ReqVo.getBeginDate(), ReqVo.getEndDate());
            //日期列表 30天 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            List<String> dateList = timeUtil.SixtyBefore();

            List<PerCardStat> visitList = new ArrayList<PerCardStat>();
            PerCardStat perCardStat = null;
            for (int i = 0; i <  dateList.size() ; i++) {
                // k1
                Map<String,Object> map = redisTemplate.opsForHash()
                        .entries("card:"+ReqVo.getCardId()+":date:"+dateList.get(i));
                perCardStat = new PerCardStat();

                if(map.size()==0){//没找到为空
//                visitList.add(perCardStat);
                    continue;
                }else{
                    if(map.get("visit")!=null){
                        int visitNum = (int) map.get("visit");
                        perCardStat.setVisitNum(visitNum);
                    }
                    if(map.get("stayNum")!=null){
                        int stayNum = (int) map.get("stayNum");
                        perCardStat.setStayNum(stayNum);
                    }
                    if(map.get("downLoadNum")!=null){
                        int downLoadNum = (int) map.get("downLoadNum");
                        perCardStat.setDownLoadNum(downLoadNum);
                    }
                    if(map.get("addContactNum")!=null){
                        int addContactNum = (int) map.get("addContactNum");
                        perCardStat.setAddContactNum(addContactNum);
                    }
                    if(map.get("reposeCardNum")!=null){
                        int reposeCardNum = (int) map.get("reposeCardNum");
                        perCardStat.setReposeCardNum(reposeCardNum);
                    }
                    if(map.get("copyWxAccount")!=null){
                        int copyWxAccountNum = (int) map.get("copyWxAccount");
                        perCardStat.setCopyWxAccount(copyWxAccountNum);
                    }
                    if(map.get("messageNum")!=null){
                        int messageNum = (int) map.get("messageNum");
                        perCardStat.setMessageNum(messageNum);
                    }
                    perCardStat.setPerDate(dateList.get(i));
                }
                // k2
                //加进列表对象
                visitList.add(perCardStat);
            }
            // 3、日均  总天数/各项数据总数
            double totaldays = dateList.size();
            double AvgVisitNum = (historyTotoalByDate.getVisitNum()) / totaldays ;
            double AvgStayNum = (historyTotoalByDate.getStayNum()) / totaldays;
            double AvgDownloadNum = (historyTotoalByDate.getDownLoadNum()) / totaldays;
            double AvgAddContactNum =(historyTotoalByDate.getAddContactNum()) / totaldays;
            double AvgReposeCardNum =  (historyTotoalByDate.getReposeCardNum()) / totaldays;
            double AvgMessageNum = (historyTotoalByDate.getMessageNum()) / totaldays;

            //转换小数点
            DemicalUtil demicalUtil = new DemicalUtil();

            AverageCardStat averageCardStat = new AverageCardStat();
            averageCardStat.setVisitNum(demicalUtil.DoubleFormat(AvgVisitNum))
                    .setStayNum(demicalUtil.DoubleFormat(AvgStayNum))
                    .setAddContactNum(demicalUtil.DoubleFormat(AvgAddContactNum))
                    .setDownLoadNum(demicalUtil.DoubleFormat(AvgDownloadNum))
                    .setReposeCardNum(demicalUtil.DoubleFormat(AvgReposeCardNum))
                    .setMessageNum(demicalUtil.DoubleFormat(AvgMessageNum));

            //日均列表 1个
            averageCardStatList.add(averageCardStat);
            HashMap<Object, Object> statMap = new HashMap<>();
            statMap.put("TotalCardStats",TotalCardStats);//累计
            statMap.put("averageCardStatList",averageCardStatList);//日均
            statMap.put("visitList",visitList);//日期列表数据

            result = JsonResult.success(statMap);
        }
        return result;
    }



    //获取6个月访客总数趋势
    @Override
    public JsonResult getSixMonthVisitStat(Integer companyId) {

        List<Integer> visitList = new ArrayList<>();
        List<Integer> clientList = new ArrayList<>();
        for (int month = 0; month < 6; month++) {
            TotalRespVo visitTotal = ebcCardStatMapper.getTotalVisitByMonth(companyId, month);
            if(visitTotal == null){
                visitList.add(0);
                continue;
            }
            visitList.add(visitTotal.getVisitTotalNum());
        }
        for (int client = 0; client < 6; client++) {
            TotalRespVo clientTotal = clientMapper.getClientTotal(companyId, client);
            if(clientTotal==null){
                clientList.add(0);
                continue;
            }
            clientList.add(clientTotal.getClientTotalNum());
        }

        //日期列表
        MyTimeUtil timeUtil = new MyTimeUtil();
        List<String> sixMonth = timeUtil.getSixMonth();
        HashMap<String, Object> map = new HashMap<>();
        map.put("DateList",sixMonth);
        map.put("visitData",visitList);
        map.put("clientData",clientList);
        return JsonResult.success(map);
    }


    //一级部门统计
    @Override
    public JsonResult getSectorStat(Integer companyId) {

        QueryWrapper<EbcCompanySector> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id",companyId);
        wrapper.eq("pid",0);
        List<EbcCompanySector> sectors = companySectorMapper.selectList(wrapper);
        List<SectorStatRespVo> sectorStatList = new ArrayList<>();
        if(sectors.size()>0){
            SectorStatRespVo sectorStatRespVo = null;

            for (EbcCompanySector sector : sectors) {
                sectorStatRespVo = new SectorStatRespVo();

//                SectorStatDto sectorNum= new SectorStatDto();
//                SectorStatDto visitActiveNum=new SectorStatDto();
//                SectorStatDto client=new SectorStatDto();
                //分别sql获取
                SectorStatDto sectorNum = ebcCardStatMapper.getSectorNum(sector.getId());
                SectorStatDto visitActiveNum = ebcCardStatMapper.getSectorVisitActiveNum(sector.getId());
                SectorStatDto client = ebcCardStatMapper.getSectorClient(sector.getId());
                if(visitActiveNum == null){
                    visitActiveNum = new SectorStatDto();
                    visitActiveNum.setActiveNum(0);
                    visitActiveNum.setVisitNum(0);
                }

                Double a = Double.NaN;
                //部门人员总数
                double secTotal = sectorNum.getSectorNum();
                DemicalUtil demicalUtil = new DemicalUtil();
                double avgVisit = visitActiveNum.getVisitNum() / secTotal;
                double avgActive = visitActiveNum.getActiveNum() / secTotal;
                double avgClient = client.getClientNum() / secTotal;

                if(a.equals(avgActive)){
                    avgActive = 0;
                }
                if(a.equals(avgVisit)){
                    avgVisit = 0;
                }
                if(a.equals(avgClient)){
                    avgClient = 0;
                }
                sectorStatRespVo
                        .setSectorName(sector.getSectorName())
                        .setSectorNum(sectorNum.getSectorNum())
                        .setClientNum(client.getClientNum())
                        .setActiveness(visitActiveNum.getActiveNum())
                        .setVisitNum(visitActiveNum.getVisitNum())
                        .setAvgActiveness(demicalUtil.DoubleFormat(avgActive))
                        .setAvgClientNum(demicalUtil.DoubleFormat(avgClient))//demicalUtil.DoubleFormat(
                        .setAvgVisitNum(demicalUtil.DoubleFormat(avgVisit));

                sectorStatList.add(sectorStatRespVo);
            }
            return JsonResult.success(sectorStatList);
        }else{
            return JsonResult.fail("获取列表为空");
        }
    }

    //二级部门
    @Override
    public JsonResult getSectorChildStat(Integer companyId) {


        QueryWrapper<EbcCompanySector> parentWrapper = new QueryWrapper<>();
        parentWrapper.eq("company_id",companyId);
        parentWrapper.eq("pid",0);
        List<EbcCompanySector> parentSector = companySectorMapper.selectList(parentWrapper);

        QueryWrapper<EbcCompanySector> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id",companyId);
        wrapper.ne("pid",0);
        //子级部门
        List<EbcCompanySector> sectors = companySectorMapper.selectList(wrapper);
        List<SectorStatRespVo> sectorStatList = new ArrayList<>();
        if(sectors.size()>0){
            SectorStatRespVo sectorStatRespVo = null;

            for (EbcCompanySector sector : sectors) {
                sectorStatRespVo = new SectorStatRespVo();
                //分别sql获取
                SectorStatDto sectorNum = ebcCardStatMapper.getSectorChildNum(sector.getId());
                SectorStatDto visitActiveNum = ebcCardStatMapper.getSectorChildVisitActiveNum(sector.getId());
                SectorStatDto client = ebcCardStatMapper.getSectorChildClient(sector.getId());
                if(visitActiveNum == null){
                    visitActiveNum = new SectorStatDto();
                    visitActiveNum.setActiveNum(0);
                    visitActiveNum.setVisitNum(0);
                }

                Double a = Double.NaN;
                //部门人员总数
                double secTotal = sectorNum.getSectorNum();
                DemicalUtil demicalUtil = new DemicalUtil();
                double avgVisit = visitActiveNum.getVisitNum() / secTotal;
                double avgActive = visitActiveNum.getActiveNum() / secTotal;
                double avgClient = client.getClientNum() / secTotal;

                if(a.equals(avgActive)){
                    avgActive = 0;
                }
                if(a.equals(avgVisit)){
                    avgVisit = 0;
                }
                if(a.equals(avgClient)){
                    avgClient = 0;
                }

                for (EbcCompanySector parentSec : parentSector) {
                    if(sector.getPid() == parentSec.getId()){
                        sectorStatRespVo.setSectorParentName(parentSec.getSectorName());
                    }
                }
                sectorStatRespVo
                        .setSectorName(sector.getSectorName())
                        .setSectorNum(sectorNum.getSectorNum())
                        .setClientNum(client.getClientNum())
                        .setActiveness(visitActiveNum.getActiveNum())
                        .setVisitNum(visitActiveNum.getVisitNum())
                        .setAvgActiveness(demicalUtil.DoubleFormat(avgActive))
                        .setAvgClientNum(demicalUtil.DoubleFormat(avgClient))//demicalUtil.DoubleFormat(
                        .setAvgVisitNum(demicalUtil.DoubleFormat(avgVisit));

                sectorStatList.add(sectorStatRespVo);
            }
            return JsonResult.success(sectorStatList);
        }else{
            return JsonResult.fail("获取列表为空");
        }
    }

    @Override
    public int roleJudge(CardStatReqVo cardStatVo) {
        List<EbcRole> roles = roleMapper.getUserRolesByUid(cardStatVo.getUserId());
        int fg = 0;
        if(roles.get(0).getRoleCode().contains("v2") || roles.get(0).getRoleCode().contains("c1")){
            if(roles.get(0).getRoleCode().contains("v2")){
                //todo  登录用户如果是员工 不计入访客统计 访客+1
                System.out.println("======员工无需添加记录=====");
               fg = 1;
            }else{
              fg = 0;
            }
        }
        return fg;
    }
}
